package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;

    //----跳转登录页面----//
    @GetMapping("/signonForm")
    public String signonForm(){
        return "account/signonForm";
    }

    //----登录检测----//
    @PostMapping("/signonCheck")
    public String signonCheck(HttpServletRequest req,@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        Account account = accountService.getAccount(username, md5pass);
//        Account account = accountService.getAccount(username, password);
        HttpSession session = req.getSession();

        String value1 = req.getParameter("vCode");
        String value2 = (String) session.getAttribute("checkcode");
        Boolean isSame = false;
        if (value2.equalsIgnoreCase(value1)) {
            isSame = true;
        }
        if (account == null || !isSame) {
            if (!isSame) {
                String tips = "Invalid Verification Code.   Signon failed.";
                model.addAttribute("message", tips);
            } else {
                String tips = "Invalid username or password.  Signon failed.";
                model.addAttribute("message", tips);
            }
            return "account/signonForm";
        } else {
            account.setPassword(null);
            String tips = "";
            model.addAttribute("message", tips);
            model.addAttribute("account",account);
            session.setAttribute("account",account);
            return "catalog/main";
        }
    }

    //----登出操作----//
    @RequestMapping("/signout")
    public String signout(HttpServletRequest req, Model model){
        Account account = null;
        HttpSession session = req.getSession();
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        return "catalog/main";
    }

    //----跳转注册----//
    @GetMapping("/registerForm")
    public String register(){
        return "account/newAccountForm";
    }

    //----新用户检测----//
    @RequestMapping("/newAccount")
    public String newAccount(HttpServletRequest req,Model model) throws UnsupportedEncodingException {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;

        String newPassword = req.getParameter("password");
        String repeatedPassword = req.getParameter("repeatedPassword");

        boolean result = false;
        if(newPassword.equals(repeatedPassword)&&newPassword != "")
        {
            result = true;
        }

        String value1=req.getParameter("vCode");
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;
        if(value2.equalsIgnoreCase(value1)){
            isSame = true;
        }

        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String country = req.getParameter("country");
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
        String listOption = req.getParameter("listOption");
        String bannerOption = req.getParameter("bannerOption");

        Account paccount = new Account();
        paccount.setUsername(username);
        String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        paccount.setPassword(md5pass);
        paccount.setFirstName(firstName);
        paccount.setLastName(lastName);
        paccount.setEmail(email);
        paccount.setPhone(phone);
        paccount.setAddress1(address1);
        paccount.setAddress2(address2);
        paccount.setCity(city);
        paccount.setState(state);
        paccount.setStatus("OK");
        paccount.setZip(zip);
        paccount.setCountry(country);
        paccount.setLanguagePreference(languagePreference);
        paccount.setFavouriteCategoryId(favouriteCategoryId);
        paccount.setListOption(Boolean.parseBoolean(listOption));
        paccount.setBannerOption(Boolean.parseBoolean(bannerOption));

        if (isSame)
        {
            if (paccount != null)
            {
                if(result)
                {
                    accountService.insertAccount(paccount);
                    return "account/signonForm";
                }
                else {
                    model.addAttribute("messageAccount", "Password Failed.");
                }
            }
            else {
                model.addAttribute("messageAccount", "No User.");
            }
        }
        else {
            model.addAttribute("messageAccount", "Invalid Verification Code.");
        }

        return "account/newAccountForm";
    }

    //----编辑资料----//
    @GetMapping("/editForm")
    public String edit(HttpServletRequest req,Model model){
        Account account= (Account) req.getSession().getAttribute("account");
        if(account == null){System.out.println("null");}
        model.addAttribute("account",account);
        return "account/editAccountForm";
    }

    //----保存信息----//
    @RequestMapping("/saveAccount")
    public String saveAccount(HttpServletRequest request,Model model) throws UnsupportedEncodingException {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        request.setCharacterEncoding("UTF-8");
        String username = account.getUsername();
        String password = request.getParameter("password");
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address1 = request.getParameter("address1");
        String address2 = request.getParameter("address2");
        String city = request.getParameter("city");
        String state = request.getParameter("state");
        String zip = request.getParameter("zip");
        String country = request.getParameter("country");
        String languagePreference = request.getParameter("languagePreference");
        String favouriteCategoryId = request.getParameter("favouriteCategoryId");
        String listOption = request.getParameter("listOption");
        String bannerOption = request.getParameter("bannerOption");

        account.setUsername(username);
        account.setPassword(password);
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setEmail(email);
        account.setPhone(phone);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setCountry(country);
        account.setLanguagePreference(languagePreference);
        account.setFavouriteCategoryId(favouriteCategoryId);
        account.setListOption(Boolean.parseBoolean(listOption));
        account.setBannerOption(Boolean.parseBoolean(bannerOption));

        accountService.updateAccount(account);

        model.addAttribute("account",account);
        session.setAttribute("account", account);
        return "account/editAccountForm";
    }

    //----验证----//
    @RequestMapping("/verificationCode")
    @GetMapping("/random.jpg")
    private void GetRandom(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("image/jpeg");
        HttpSession session = request.getSession();
        int width = 60;
        int height = 20;

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[4];
        for (int i = 0; i < 4; i++) {
            int rand = (int) (Math.random() * 36);
            rands[i] = chars.charAt(rand);
        }

        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);

        for (int i = 0; i < 120; i++) {
            int x = (int) (Math.random() * width);
            int y = (int) (Math.random() * height);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            g.setColor(new Color(red, green, blue));
            g.drawOval(x, y, 1, 0);
        }
        g.setColor(Color.BLACK);
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));

        g.drawString("" + rands[0], 1, 17);
        g.drawString("" + rands[1], 16, 15);
        g.drawString("" + rands[2], 31, 18);
        g.drawString("" + rands[3], 46, 16);
        g.dispose();

        ServletOutputStream sos = response.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] buffer = baos.toByteArray();
        response.setContentLength(buffer.length);
        sos.write(buffer);
        baos.close();
        sos.close();

        session.setAttribute("checkcode", new String(rands));
    }

    //----检测用户名重复----//
    @GetMapping("/usernameIsExist")
    public void usernameIsExist(@RequestParam("username") String username, HttpServletResponse response){

        if(username.equals("")){
            return;
        }
        Account account = accountService.getAccount(username);
        try{
            response.setContentType("text/json");
            PrintWriter out = response.getWriter();
            String msg ;
            if(account != null){
                msg = "Exist";
                String str = JSON.toJSONString(msg);
                out.println(str);
            }else{
                msg = "NotExist";
                String str = JSON.toJSONString(msg);
                out.println(str);
            }
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}